import controller.base
import datetime
from util.misc import *
import json

class MessageHandler(controller.base.BaseHandler):
    def get(self):
        sql = 'SELECT * FROM notifications LIMIT 100'
        res = self.db.query(sql)
        ntfs = []
        for ntf in res:
            ntfs.append({
                "MessageID": ntf["id"],
                "MessageContent": ntf["text"],
                "CreatedAt": ntf["createTime"].strftime("%Y-%m-%d %H:%M:%S"),
                "Url": ntf["url"],
            })
        data = {"Messages": ntfs}
        self.rsp(0, data)

    def post(self):
        if not self.checkAdmin():
            self.rsp(1, msg="not admin")
        content = self.get_body_para("content")
        url = self.get_body_para("url")

        sql = "INSERT INTO notifications (text,url,createTime) VALUES (%s,%s,%s)"
        res = self.db.insert(sql, content, url, datetime.datetime.now().strftime("%y-%m-%d %H:%M:%S"))

        self.rsp(0)

    def checkAdmin(self):
        if 'Admin' in self.request.headers and self.request.headers['Admin'] == "asdf1234~":
            return True
        else:
            return False


class VerisonHandler(controller.base.BaseHandler):
    def get(self, type):
        sql = 'SELECT * FROM version WHERE type = %s'
        res = self.db.get(sql, type)

        data = {
            "latestVersionNo": res['latestVersionNo'],
            "latestVersionName": res['latestVersionName'],
            "minVersionNo": res['minVersionNo'],
            "minRunMinVersionName": res['minRunMinVersionName'],
            "Describe": res['Description'],
            "DownloadUrl": res['DownloadUrl']
        }
        self.rsp(0, data)


class FeedbackHandler(controller.base.AuthHandler):
    def post(self):
        content = self.get_body_para("content")

        if content is None:
            self.rsp(7, msg="parameter error")
            return

        mail_content = "您收到一条新的用户反馈，内容如下：\r\n" + content
        send_mail('用户反馈提醒', mail_content)

        sql = "INSERT INTO feedback (content,fromId,createAt) VALUES (%s,%s,%s)"
        res = self.db.insert(sql, content, self.user["id"], datetime.datetime.now().strftime("%y-%m-%d %H:%M:%S"))

        self.rsp(0)

